package cn.gqr.service.impl;

import cn.gqr.entity.Role;
import cn.gqr.service.RemoteUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Primary
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //基于用户名获取用户信息
        cn.gqr.entity.User user = remoteUserService.selectUserByUsername(username);
        if(user==null) throw new UsernameNotFoundException("用户不存在");


        //查询用户角色
        List<Role> roles = remoteUserService.selectUserRole(user.getId());

        List<GrantedAuthority> authorityList = new ArrayList();

        User userinfo = null;

        //前台用户登录权限
        if(roles.size()==1){

            String roleName = roles.get(0).getRoleName();

            if("user".equals(roleName)){

                authorityList.add(new SimpleGrantedAuthority(roleName));

                userinfo = new User(
                        JSON.toJSONString(user), user.getPassword(),
                        true,true , true,
                        user.getClosed()==0,authorityList
                );

                return  userinfo;
            }

        }

        //后台用户
        for(Role role: roles){
            //添加角色
            authorityList.add(new SimpleGrantedAuthority(role.getRoleName()));
            //根据角色查询权限
            List<String> permissions = remoteUserService.selectUserPermissions(role.getId());

            for( String permission : permissions){
                //添加权限
                authorityList.add(new SimpleGrantedAuthority(permission));
            }
        }

        userinfo = new User(
            JSON.toJSONString(user), user.getPassword(),
            true,true , true,
            user.getClosed()==0,authorityList
        );

        return userinfo;
    }

}
